<template>
  <div>
    <el-dialog :title="title" :visible="visible" @close="handleClose" width="600px">
      <el-form :model="formImg" label-position="right" :rules="rules" ref="formImg">
        <el-row>
          <el-col :span="24">
            <el-form-item label="图片code" prop="picClassCode" :label-width="formLabelWidth">
              <el-input v-model="formImg.picClassCode" placeholder="请输入图片code"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图标名称" prop="picClassName" :label-width="formLabelWidth">
              <el-input v-model="formImg.picClassName" placeholder="请输入图标名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图标类型" prop="picTypeCode" :label-width="formLabelWidth">
              <el-select clearable v-model="formImg.picTypeCode" style="width: 100%;">
                <el-option v-for="(item, index) in typePicList" :key="index" :value="item.picTypeCode"
                           :label="item.picTypeName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="路径" prop="picPath" :label-width="formLabelWidth">
              <image-upload-one v-model="formImg.picPath"/>
              <!--              <el-upload class="upload-demo" action :http-request="uploadFile" ref="upload" :limit="fileLimit"-->
              <!--                         :file-list="fileList" :before-upload="beforeUpload" :show-file-list="false">-->
              <!--                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>-->
              <!--              </el-upload>-->
              <!--              <img v-if="formImg.picPath" :src="formImg.picPath ? formImg.picPath : ''"></img>-->
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  basicPicInfoSave, //保存图标
  basicPicInfoUpdate,
  findBasicPicTypeAll, //获取类型
  upLoad
} from '@/api/basic/PersonnelInformation.js'

export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      fileList: [], //上传数据列表保存
      fileType: ["png", "jpg", "bmp", "jpeg"],
      fileLimit: 5,
      formImg: {
        picClassCode: '',
        picClassName: '',
        picPath: ''
      },
      typePicList: [],
      imageUrl: '',
      title: '新增图标',
      formLabelWidth: '110px',
      rules: {
        picClassCode: [{
          required: true,
          message: '请输入图标代码',
          trigger: 'blur'
        }],
        picClassName: [{
          required: true,
          message: '请输入图标名称',
          trigger: 'blur'
        }],
        picTypeCode: [{
          required: true,
          message: '请选择图标类型',
          trigger: 'blur'
        }]
      },
    };
  },
  created() {
    this.typeList();
  },
  methods: {
    //上传文件的事件
    uploadFile(item) {
      let FormDatas = new FormData()
      FormDatas.append('file', item.file);
      upLoad(FormDatas).then((res) => {
        this.$message.success('上传成功')
        this.formImg.picPath = res.url;
      }).catch(() => {
        this.$message.error(res.msg)
      })
    },
    //获取图标类型
    typeList() {
      findBasicPicTypeAll().then(res => {
        this.typePicList = res.data;
      })
    },
    //上传文件之前
    beforeUpload(file) {
      if (file.type != "" || file.type != null || file.type != undefined) {
        //截取文件的后缀，判断文件类型
        const FileExt = file.name.replace(/.+\./, "").toLowerCase();
        //计算文件的大小
        const isLt5M = file.size / 1024 / 1024 < 50; //这里做文件大小限制
        //如果大于50M
        if (!isLt5M) {
          this.$message.error('上传文件大小不能超过 50MB!');
          return false;
        }
        //如果文件类型不在允许上传的范围内
        if (this.fileType.includes(FileExt)) {
          return true;
        } else {
          this.$message.error("上传文件格式不正确!");
          return false;
        }
      }
    },
    //获取当前行信息
    openDialog(type, val) {
      this.title = type === 'edit' ? '编辑图标' : '新增图标';
      // 根据类型区分新增和编辑逻辑
      if (type === 'edit' && val) {
        this.formImg = {...val};
      } else {
        this.formImg = {
          picClassCode: '',
          picClassName: '',
          picPath: ''
        }
      }
    },
    // 提取重置表单的逻辑
    handleClose() {
      // 通过事件通知父组件更新visible值，触发update:visible事件
      this.$emit('update:visible', false);
      this.$nextTick(() => {
        this.$refs.formImg.resetFields();
      })
    },
    //提交表单
    submit() {
      this.$refs.formImg.validate((valid) => {
        if (valid) {
          const apiMethod = this.title === '新增图标' ? basicPicInfoSave : basicPicInfoUpdate;
          // 调用相应的 API 方法
          apiMethod(this.formImg).then(res => {
            this.$emit('addSuccess'); // 通知父组件添加成功
            this.$message({
              message: res.msg, // 显示成功消息
              type: 'success',
            });
            // 提交成功后可以选择清空表单
            this.handleClose();
          }).catch(err => {
            this.$message({
              message: err?.msg || '操作失败', // 捕获错误信息
              type: 'error',
            });
          });
        } else {
          // 校验失败
          return false;
        }
      });
    }
  },
};
</script>

<style scoped>
img {
  width: 50px;
  height: 50px;

}
</style>
